package com.ppsea;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.json.JSONException;
import org.json.JSONObject;

public class Utils {
	public final static String FXWR_XIAN = "http://fxwr.nj.twsapp.com";
	public final static String FXWR_MO = "http://fxwrb.2022n.nj.twsapp.com";
	public final static String FXWR_HUAI = "http://fxwrc.2022m.nj.twsapp.com";
	public final static String XMY_URL = "http://xmy.2022m.nj.twsapp.com";
	
	public static String encode(String str, String pswd, String proxyKey) throws NoSuchAlgorithmException {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		if (pswd == null)
			pswd = "";
		byte[] d = md5.digest((pswd + proxyKey + str).getBytes());
		return byte2hex(d, d.length - 4, d.length);
	}

	public static String encode(String param) throws NoSuchAlgorithmException {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		byte[] d = md5.digest(param.getBytes());
		return byte2hex(d, d.length - 4, d.length);
	}

	public static String random() {
		return String.valueOf(new Random().nextInt(10000));
	}

	public static String byte2hex(byte[] b, int start, int end) {
		String hs = "";
		String tmp = "";
		for (int n = start; n < end; n++) {
			tmp = Integer.toHexString(b[n] & 0xFF);
			if (tmp.length() == 1)
				hs = hs + "0" + tmp;
			else {
				hs = hs + tmp;
			}
		}
		tmp = null;
		return hs;
	}

	public static String encodeAndRandom(String str, String pswd, String proxyKey) throws NoSuchAlgorithmException {
		return encode(str, pswd, proxyKey) + "-" + (int) (System.currentTimeMillis() / 1000L);
	}
	
	public static String encodeAndRandom(String str, String pswd, String proxyKey, int time) throws NoSuchAlgorithmException {
	    return encode(time + "-" + str, pswd, proxyKey) + "-" + time;
	}

	/**
	 * 非仙书签生成
	 * @param uid
	 * @param pwd
	 * @param zone
	 * @return
	 */
	public static String generateFxwrBookMark(String uid, String pwd, int zone) {
		String md5Key = "x@$^%!A2#";
		String domain = FXWR_XIAN;// old domain fxwr.3g.qq.com
		if (zone == 2) {
			md5Key = "y@$^%!A2#";
			domain = FXWR_MO;
		} else if (zone == 3) {
			md5Key = "z@$^%!B2#";
			domain = FXWR_HUAI;
		}
		try {
			return domain
					+ "/p?"
					+ encodeAndRandom(new StringBuilder("p_M/").append(uid)
							.append("/").toString(), pwd, md5Key) + "-p_M/"
					+ uid + "/";
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static String specialFxwrBookMark(String uid, int zoneId, boolean isLocal, String cmd, String ps) {
		String md5Key = "x@$^%!A2#";
		String domain = FXWR_XIAN;// old domain fxwr.3g.qq.com
		if (zoneId == 2) {
			md5Key = "y@$^%!A2#";
			domain = FXWR_MO;
		} else if (zoneId == 3) {
			md5Key = "z@$^%!B2#";
			domain = FXWR_HUAI;
		}
		if(isLocal){
			domain = "http://localhost:8080";
		}
		String pwd = Utils.queryPlayerPwd(uid, zoneId);
		try {
			return domain
					+ "/p?"
					+ encodeAndRandom(new StringBuilder(cmd).append("/")
							.append(uid).append("/").append(ps).toString(), pwd, md5Key)
					+ "-"+cmd+"/" + uid + "/"+ ps;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 仙魔妖书签生成
	 * @param playerId
	 * @param pwd
	 * @param zoneId
	 * @return
	 */
	public static String generateXmyBookMark(String playerId, String pwd, int zoneId) {
		String md5Key = "QA!@#$%*X00";
		String domain = XMY_URL;
		if (zoneId == 1) {
			md5Key = "QA!@#$%*X01";
		} else if (zoneId == 2) {
			md5Key = "QA!@#$%*X02";
		}
		int verifyTime = (int) (System.currentTimeMillis() / 1000L);
		try {
			//http://xmy.2022m.nj.twsapp.com/0/p?e5e2bb6b-1378287314-p_M/257/
			return domain +"/"+ zoneId + "/p?"	+ 
					encodeAndRandom(new StringBuilder("p_M/").append(playerId).append("/").toString(), pwd, md5Key, verifyTime)
					+"-p_M/"+ playerId + "/";
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static String specialXmyBookMark(String playerId, int zoneId, boolean isLocal, String cmd, String ps){
		String md5Key = "QA!@#$%*X00";
		String domain = XMY_URL;
		if(isLocal){
			domain = "http://localhost:16000";
		}
		if (zoneId == 1) {
			md5Key = "QA!@#$%*X01";
		} else if (zoneId == 2) {
			md5Key = "QA!@#$%*X02";
		}
		ps = ps.isEmpty() ? "" : ps + "/";
		int verifyTime = (int) (System.currentTimeMillis() / 1000L);
		try {
			JSONObject playerJson = Utils.queryXMYPlayer(String.valueOf(playerId), zoneId);
			if(playerJson == null){
				return null;
			}
			String pwd = playerJson.getString("password").toString();
			return domain +"/"+ zoneId + "/p?"	+ 
					encodeAndRandom(
							new StringBuilder(cmd).append("/")
							.append(playerId).append("/").append(ps).toString(), pwd, md5Key, verifyTime)
					+"-"+ cmd +"/"+ playerId + "/" + ps;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String QQ2Uid(String qq) {
		String url = "http://221.179.19.167:9290/uid2uin.jsp?uin=" + qq
				+ "&cpid=1024&gameid=2022&pwd=zhsh%401024&inner=true&getuid=1";
		HttpClient httpclient = new DefaultHttpClient();
		// 设置超时
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 500);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,500);
		HttpGet get = new HttpGet(url);
		try {
			HttpResponse response = httpclient.execute(get);
			HttpEntity entity = response.getEntity();
			InputStream inputStream = entity.getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			String message = null;
			while ((message = br.readLine()) != null) {
				if (message.trim().contains(". [")) {
					int index = message.lastIndexOf("]");
					message = message.substring(index - 32, index);
					String str1 = message;
					return str1;
				}
			}

		} catch (Exception localException) {
		} finally {
			get.abort();
			httpclient.getConnectionManager().closeExpiredConnections();
		}
		return null;
	}

	public static String Uid2QQ(String uid) {
		String url = "http://221.179.19.167:9290/uid2uin.jsp?uid=" + uid
				+ "&cpid=1024&gameid=2022&pwd=zhsh%401024&inner=true&getuin=1";
		HttpClient httpclient = new DefaultHttpClient();
		// 设置超时
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 500);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,500);
		HttpGet get = new HttpGet(url);
		try {
			HttpResponse response = httpclient.execute(get);
			HttpEntity entity = response.getEntity();
			InputStream inputStream = entity.getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					inputStream, "UTF-8"));
			String message = null;
			while ((message = br.readLine()) != null) {
				if (message.trim().contains(". [")) {
					int startIndex = message.lastIndexOf("|");
					int endIndex = message.lastIndexOf("]");
					message = message.substring(startIndex + 1, endIndex);
					String str1 = message;
					return str1;
				}
			}

		} catch (Exception localException) {
		} finally {
			get.abort();
			httpclient.getConnectionManager().closeExpiredConnections();
		}
		return null;
	}

	public static String queryPlayerPwd(String uid, int zone) {
		String domain = FXWR_XIAN;
		if (zone == 2) {
			domain = FXWR_MO;
		} else if (zone == 3) {
			domain = FXWR_HUAI;
		}

		String url = domain + "/admin";
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 500);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,500);
		HttpPost post = new HttpPost(url);
		try {
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			params.add(new BasicNameValuePair("cmd", "m_QP|" + uid));
			post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

			HttpResponse response = httpclient.execute(post);
			HttpEntity entity = response.getEntity();
			InputStream inputStream = entity.getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					inputStream, "UTF-8"));

			String message = null;
			if ((message = br.readLine()) != null)
				;
			JSONObject json = new JSONObject(message);

			return json.get("passwd").toString();
		} catch (Exception localException) {
		} finally {
			post.abort();
			httpclient.getConnectionManager().closeExpiredConnections();
		}
		return null;
	}
	
	public static JSONObject queryXMYPlayer(String id, int zoneId) {
		String domain = XMY_URL;

		String url = domain +"/"+ zoneId +"/admin/"+ zoneId +"/";
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 500);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,500);
		HttpPost post = new HttpPost(url);
		try {
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			params.add(new BasicNameValuePair("cmd", "m_QP|" + id));
			post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

			HttpResponse response = httpclient.execute(post);
			HttpEntity entity = response.getEntity();
			InputStream inputStream = entity.getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

			String message = null;
			if ((message = br.readLine()) != null)
				;
			JSONObject json = new JSONObject(message);

			return new JSONObject(json.get("player").toString());
		} catch (Exception localException) {
		} finally {
			post.abort();
			httpclient.getConnectionManager().closeExpiredConnections();
		}
		return null;
	}
}